const {
  createGoodsCategoryService,
  createGoodsService,
  findGoodsDetailIdService,
} = require("../../service/goods");
const { ErrorRes, SuccessRes } = require("../../res-model/index");
const {
  createGoodsCategoryFailInfo,
  createGoodsFailInfo,
  findGoodsDetailInfo,
} = require("../../res-model/failInfo/goods");
/**
 * @description 创建产品
 * @returns
 */
async function createGoods(data) {
  console.log("data", data);
  // authorName 默认admin
  const { cId, name } = data;
  if (!cId) {
    // 标题不能为空
    return new ErrorRes(createGoodsFailInfo, "产品分类Id不能为空");
  }
  if (!name) {
    // 标题不能为空
    return new ErrorRes(createGoodsFailInfo, "产品名称不能为空");
  }
  let newGoods;
  try {
    newGoods = await createGoodsService(data);
  } catch (ex) {
    console.error("创建产品失败", ex);
    return new ErrorRes(createGoodsFailInfo); // 数据库错误
  }
  // 创建失败
  if (newGoods == null)
    return new ErrorRes(createGoodsFailInfo, "创建产品失败");
  // 产品详情
  const { _id: gid } = newGoods;

  // 创建成功
  return new SuccessRes(newGoods);
}

/**
 * @description 创建产品分类
 * @returns
 */
async function createGoodsCategory(data) {
  const { name } = data;
  if (!name) {
    // 标题不能为空
    return new ErrorRes(createGoodsCategoryFailInfo, "产品分类名不能为空");
  }
  let newGoodsCategory;
  try {
    newGoodsCategory = await createGoodsCategoryService(data);
  } catch (ex) {
    console.error("创建产品分类失败", ex);
    return new ErrorRes(createGoodsCategoryFailInfo); // 数据库错误
  }
  // 创建失败
  if (newGoodsCategory == null)
    return new ErrorRes(createGoodsCategoryFailInfo, "创建产品分类失败");

  // 创建成功
  return new SuccessRes(newGoodsCategory);
}

/**
 * @description 创建产品详情
 * @returns
 */
async function createGoodsDetail(data) {
  console.log("data", data);
  // authorName 默认admin
  const { cId, name } = data;
  if (!cId) {
    // 标题不能为空
    return new ErrorRes(findGoodsDetailInfo, "产品详情Id不能为空");
  }
  if (!name) {
    // 标题不能为空
    return new ErrorRes(findGoodsDetailInfo, "产品详情不能为空");
  }
  let newGoods;
  try {
    newGoods = await findGoodsDetailIdService(data);
  } catch (ex) {
    console.error("创建产品失败", ex);
    return new ErrorRes(createGoodsFailInfo); // 数据库错误-
  }
  // 创建失败
  if (newGoods == null)
    return new ErrorRes(createGoodsFailInfo, "创建产品详情失败");
  // 产品详情
  const { _id: gid } = newGoods;

  // 创建成功
  return new SuccessRes(newGoods);
}

module.exports = {
  createGoods,
  createGoodsCategory,
  createGoodsDetail
};
